local desc_1v1 = [[
  # 龙舟争粽模式简介

  端午节专属模式

  ___
    游戏开始时，每人获得4个粽子，玩家均拥有一支0m处的龙舟，龙舟率先达到100m的玩家获胜！

    每名玩家回合开始前，可以选择制作5个粽子并跳过本回合或吃若干数目的粽子并获得所吃粽子数+1的体力，玩家出牌阶段每使用一张牌后会消耗一点体力并使龙舟前进1m。玩家体力为0时，不能使用或打出牌。

    回合结束时，玩家消耗所有剩余体力使龙舟行进（2*消耗体力）m。

    玩家造成伤害时，使龙舟行进2m，同时受伤角色会受到屈原赐福而获得1个粽子。角色死亡时，死亡角色修整一回合，伤害来源龙舟前进6m。

    每轮结束时,所有存活角色龙舟依次行进玩家当前体力数m。
  


]]

local T = require "packages/jbs/record/Theorem"

-- FIXME: Disable same convert by param or extra data
local function rm(generals, g)
  local gt = Fk.generals[g].trueName
  for i, v in ipairs(generals) do
    if Fk.generals[v].trueName == gt then
      table.remove(generals, i)
      return
    end
  end
end

--
--技能获得
local function reward_Newskill(room,players)
  local room=room
  for _, player in ipairs(players) do
  local existingGenerals = {}
  table.forEach(room.players, function(p)
    table.insertTable(existingGenerals, {p.general, p.deputyGeneral})
  end)
  local generals = table.map(Fk:getGeneralsRandomly(10, Fk:getAllGenerals(), existingGenerals,
    (function(p) return false end)), function(g) return g.name end)
  generals = table.random(generals, math.min(4, #generals))
  local skills = {}
  local choices = {}
for _, general_name in ipairs(generals) do
local general = Fk.generals[general_name]
local g_skills = {}
--加载技能
for _, skill in ipairs(general.skills) do
  if not (table.contains({Skill.Limited, Skill.Wake, Skill.Quest}, skill.frequency) or skill.lordSkill) then
    table.insertIfNeed(g_skills, skill.name)
  end
end
for _, s_name in ipairs(general.other_skills) do
  local skill = Fk.skills[s_name]
  if not (table.contains({Skill.Limited, Skill.Wake, Skill.Quest}, skill.frequency) or skill.lordSkill)  then
    table.insertIfNeed(g_skills, skill.name)
  end
end
table.insertIfNeed(skills, g_skills)
if #choices == 0 and #g_skills > 0 then
  choices = {g_skills[1]}
end
end

if #choices > 0 then
  player.request_data = json.encode({
    path = "packages/tenyear/qml/ChooseGeneralSkillsBox.qml",
    data = {
      generals, skills, 1, 1, "jbsfire__reward",true
    },
  })
  player.default_reply = table.random(skills, 1)
end

--循环
end
room:doBroadcastRequest("CustomDialog", players)

for _, p in ipairs(players) do
  if p.id>0 then
  local choice = p.reply_ready and json.decode(p.client_reply) or {"jiang"}
  room:handleAddLoseSkills(p, table.concat(choice, "|") , nil)
  p:drawCards(2)
  end
end

end

local function getai(players)
  local targets = {}
  for _, p in ipairs(players) do
      if p.id<0 then
          table.insert(targets, p.id)
        end
  end
  return targets
  
end

--buff表

local m_1v1_getLogic = function()
  local m_1v1_logic = GameLogic:subclass("jbszongzi_logic")
  function m_1v1_logic:prepareDrawPile()
    local room = self.room
    local allCardIds = Fk:getAllCardIds()
    --重新过滤卡组
    local filterCardIds = {}
    local while_cards = {"standard","standard_cards","maneuvering","tenyear_token","mobile_derived","ol_token","overseas_token","jbs_cards"}
    local blacklist = { "amazing_grace"}
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(while_cards,card.package.name) or table.contains(blacklist, card.name) then
          table.removeOne(allCardIds, id)
          table.insert(room.void, id)
          room:setCardArea(id, Card.Void, nil)
        end
      if table.contains(while_cards,card.package.name) and not table.contains(blacklist, card.name)  then
        if not card.is_derived then
          table.insert(filterCardIds,id)
        end
      end
    end
    end
     
  
  
    local seed = math.random(2 << 32 - 1)
    table.shuffle(filterCardIds,seed)
    room.draw_pile = filterCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
    room:doBroadcastNotify("PrepareDrawPile", seed)

  end
  
  --身份分配
  function m_1v1_logic:assignRoles()
    local room = self.room
    local n = #room.players
    local ais=getai(room.players)
    if room:getSettings('enableDeputy')  then
    local roles = table.random {
      { "loyalist", "rebel", "rebel", "loyalist" , "loyalist",  "rebel", "rebel","loyalist"},
      { "rebel", "loyalist", "loyalist", "rebel","rebel", "loyalist" , "loyalist","rebel"},
    }

  
    for i = 1, n do
      local p = room.players[i]
      p.role = roles[i]
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end
    self.start_role = roles[1]
    else
      for i = 1, n do
        local p = room.players[i]
        if i%2~=0 then
          p.role ="loyalist"
        else
          p.role = "rebel"
        end
        room:setPlayerProperty(p, "role_shown", true)
        room:broadcastProperty(p, "role")
      end
      self.start_role = room.players[1].role
    end

    room.players[1].role = "lord"

    -- for adjustSeats
    -- for adjustSeats
  end
  function m_1v1_logic:chooseGenerals()
    local room = self.room
    local generalNum = room:getSettings('generalNum')
    local n = room:getSettings('enableDeputy') and 1 or 1
    local lord = room:getLord()
    local lord_generals = {"jbshoulang__quyuan"}
  
    if lord ~= nil then
      room.current = lord
      room:setBanner("@[:]jbsfire_rule","jbszongzi-intro")
      room:setBanner("@jbszongzi_blueprocess",0 )--忠臣得分
      room:setBanner("@jbszongzi_redprocess",0 )--反贼得分
      
      lord.role = self.start_role
    end
    local klboss_generals={}
    local nonlord = room.players
    room.goalnum=#nonlord*20
    local generals = room:getNGenerals(#nonlord * generalNum)
    room:setBanner("@jbszongzi_goalprocess",room.goalnum )--获胜目标得分
    table.shuffle(generals)
    for i, p in ipairs(nonlord) do
      if p.id>0 then
      local arg = table.slice(generals, (i - 1) * generalNum + 1, i * generalNum + 1)
      p.request_data = json.encode{ arg, n }
      p.default_reply = table.random(arg, n)
      elseif p.id<0 then
        table.insert(klboss_generals,table.remove(lord_generals, 1))

        p.request_data = json.encode({ klboss_generals, 1 })
        p.default_reply = klboss_generals[1]
      end
    end
  
    room:notifyMoveFocus(nonlord, "AskForGeneral")
    room:doBroadcastRequest("AskForGeneral", nonlord)
  
    local selected = {}
    for _, p in ipairs(nonlord) do
      if p.general == "" and p.reply_ready then
        local general_ret = json.decode(p.client_reply)
        local general = general_ret[1]
        local deputy = general_ret[2]
        table.insertTableIfNeed(selected, general_ret)
        room:setPlayerGeneral(p, general, true, true)
        room:setDeputyGeneral(p, deputy)
      else
        room:setPlayerGeneral(p, p.default_reply, true, true)
      end
      p.default_reply =""
    end
  
    generals = table.filter(generals, function(g) return not table.contains(selected, g) end)
    room:returnToGeneralPile(generals)
  
    room:askForChooseKingdom(nonlord)
  end



  function m_1v1_logic:broadcastGeneral()--
    local room = self.room
    local players = room.players
  
    for _, p in ipairs(players) do
      assert(p.general ~= "")
      local general = Fk.generals[p.general]
      local deputy = Fk.generals[p.deputyGeneral]
      p.maxHp = p:getGeneralMaxHp()
      p.hp = deputy and math.floor((deputy.hp + general.hp) / 2) or general.hp
      p.shield = general.shield 
      --room:broadcastProperty(p, "role")     
      room:broadcastProperty(p, "general")
      room:broadcastProperty(p, "kingdom")
      room:broadcastProperty(p, "deputyGeneral")
      room:broadcastProperty(p, "maxHp")
      room:broadcastProperty(p, "hp")
      room:broadcastProperty(p, "shield")
      room:setPlayerMark(p,"@jbs_zongzi",3)
     
    end
  end
  function m_1v1_logic:attachSkillToPlayers()
    local room = self.room
    --[[
    if room:getSettings('enableDeputy') then
      return true
    end
    --]]
    local players = room.players
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: "..skillName.." doesn't exist!")
        return
      end
      if skill.lordSkill and (player.role ~= "lord" or #room.players < 5) then
        return
      end
  
      if #skill.attachedKingdom > 0 and not table.contains(skill.attachedKingdom, player.kingdom) then
        return
      end
  
      room:handleAddLoseSkills(player, skillName, nil, false)
    end
    for _, p in ipairs(room.alive_players) do
      local skills = Fk.generals[p.general].skills
      for _, s in ipairs(skills) do
        addRoleModSkills(p, s.name)
      end
      for _, sname in ipairs(Fk.generals[p.general].other_skills) do
        addRoleModSkills(p, sname)
      end
  
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        skills = deputy.skills
        for _, s in ipairs(skills) do
          addRoleModSkills(p, s.name)
        end
        for _, sname in ipairs(deputy.other_skills) do
          addRoleModSkills(p, sname)
        end
      end
      addRoleModSkills(p, "zongzi_makezong")
    end
  end


  return m_1v1_logic
end

--增加路程
local addlongzhou=function (player,n)
  local n=n or 1
  local room=player.room
  local s="@jbszongzi_blueprocess"
  if player.role=="loyalist" then
    s="@jbszongzi_blueprocess"
  elseif player.role=="rebel" then
    s="@jbszongzi_redprocess"
  end
  local x=room:getBanner(s) or 0
  local y=x+n
  room:setBanner(s,y)
  if y>=room.goalnum then
    room:gameOver(player.role)
  end

end

--制粽技能

local mietian=fk.CreateActiveSkill{
  name = "zongzi_makezong",
  anim_type = "offensive",
  prompt="弃置点数和为5的倍数的牌来制作粽子！",
  min_card_num = 1,
  max_card_num=999,
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter  =  function(self, to_select, selected)
    return true
  end,
  feasible = function (self, selected, selected_cards)
    
    return  T.cardnumbersum(selected_cards)%5==0
  end,
  on_use = function(self, room, effect)
   local n= T.cardnumbersum(effect.cards)//5
   local player = room:getPlayerById(effect.from)
   room:throwCard(effect.cards, self.name, player, player)
   room:addPlayerMark(player,"@jbs_zongzi",n)

 
    --end
  end,
}
Fk:addSkill(mietian)

local m_1v1_rule = fk.CreateTriggerSkill{
  name = "#jbszongzi_rule",
  priority = 0.001,
  refresh_events = {fk.Damage,fk.GameStart,fk.GameOverJudge,fk.BeforeTurnStart,fk.CardUseFinished,fk.RoundEnd,fk.TurnEnd,
  fk.BeforeGameOverJudge,fk.BuryVictim},
  can_refresh = function(self, event, target, player, data)
    if event==fk.Damage then
      return target == player and data.to ~=player and data.to.role~=player.role
    elseif event==fk.TurnEnd then
      return target==player and player:getMark("@jbs_zongzienergy")>0 
    elseif event==fk.CardUseFinished then
      return target==player and player.phase ~= Player.NotActive
    else
      return target == player
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      local players=room.alive_players
      room:doBroadcastNotify("ShowToast", "赛龙舟！每回合记得吃粽子获得体力出牌哦！")
      --reward_Newskill(room,players)

      --执行奖惩
    elseif event==fk.BeforeGameOverJudge then 
      
      player._splayer:setDied(false)
      room:setPlayerRest(player, 1)
      if data.damage and data.damage.from and not data.damage.from.dead and  data.damage.from.role~=player.role then
      addlongzhou(data.damage.from,20)

      end
    elseif event==fk.BuryVictim then 
      room:setTag("SkipGameRule", true)
    elseif event==fk.Damage then
      addlongzhou(player,5)
      if data.to then 
        room:addPlayerMark(data.to,"@jbs_zongzi",1)
        data.to:drawCards(1,self.name)
      end
    --每轮结束走路

    elseif event==fk.RoundEnd then
      local n=0
      for _, p in ipairs(room.alive_players) do
        n=p.hp
        addlongzhou(p,n)

      end

    --回合结束清理
    elseif event==fk.TurnEnd then
      local n=player:getMark("@jbs_zongzienergy")
      room:removePlayerMark(player,"@jbs_zongzienergy",n)
      addlongzhou(player,n*2)


      --消耗体力
    elseif event==fk.CardUseFinished then
      if player:getMark("@jbs_zongzienergy")>0 then
        room:removePlayerMark(player,"@jbs_zongzienergy",1)
        addlongzhou(player,1)
      end
      if player:getMark("@jbs_zongzienergy")==0 then
        room:setPlayerMark(player,"@@buqun__dongjie-turn",1)
      end
    --回合开始选择
    elseif event==fk.BeforeTurnStart then
      local number
      local choices = {"prezongzi"}
      
      for i = 1, math.min(99,player:getMark("@jbs_zongzi")) do
          table.insert(choices, tostring(i))
      end
      local  choice=room:askForChoice(player, choices, self.name, "决定要吃多少粽子！")

      if choice=="prezongzi" then
        room:doBroadcastNotify("ShowToast", "做粽子！")
        local nonlord = room.alive_players
        for _, p in ipairs(nonlord) do
          if p.role==player.role  then
            room:addPlayerMark(p,"@jbs_zongzi",1)
          end
        end
        --room:addPlayerMark(player,"@jbs_zongzienergy",1)
        player:skip(Player.Play)
      --elseif choice=="Cancel" then
      else
      number = tonumber(choice) ---@type integer
      room:doBroadcastNotify("ShowToast", "我吃吃吃！")

      room:addPlayerMark(player,"@jbs_zongzienergy",number)
      room:removePlayerMark(player,"@jbs_zongzi",number)
      end
      
    elseif event == fk.GameOverJudge then
    room:setTag("SkipGameRule", true)
    if #room.alive_players == 1 then
      local winner = Fk.game_modes[room:getSettings('gameMode')]:getWinner(player)
      if winner ~= "" then
        room:gameOver(winner)
        return true
      end
    end

    end


  end,
}





local m_1v1_mode = fk.CreateGameMode{
  name = "jbszongzi_mode",
  minPlayer = 4,
  maxPlayer = 8,
  rule = m_1v1_rule,
  logic = m_1v1_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "#left two alive", passed = #Fk:currentRoom().alive_players == 2 } }
    return surrenderJudge
  end,
  winner_getter = function(self, victim)
    local room = victim.room
    local alive = table.filter(room.alive_players, function(p)
      return not p.surrendered
    end)
    if #alive > 1 then return "" end
    alive[1].role = "renegade" --生草
    return "renegade"
  end,
}
-- extension:addGameMode(m_1v1_mode)
Fk:loadTranslationTable{
  ["jbszongzi_mode"] = "龙舟争粽",
  [":jbszongzi_mode"] = desc_1v1,

  ["jbszongzi-intro"]="龙舟争粽",
  [":jbszongzi-intro"]=[[ 游戏开始时，每人分为2队并获得3个粽子，每队拥有1龙舟，龙舟率先达到游戏人数*20的队伍！获胜！<br>
  每名玩家回合开始前，可以选择为所有队友各制作1个粽子并跳过本回合出牌阶段或吃若干数目的粽子并获得所吃粽子数的体力；
  <br>玩家出牌阶段每使用一张牌后会消耗一点体力并使龙舟前进1m。玩家体力为0时，不能使用或打出牌。
  <br>结束阶段，玩家消耗所有体力使龙舟行进（2*消耗体力）m。
  <br>玩家对敌人造成伤害时，使龙舟行进5m，同时受伤角色会受到屈原赐福而获得1个粽子并摸1张牌。角色死亡时，死亡角色修整一回合，伤害来源龙舟前进20m。
  <br>每轮结束时,所有存活角色依次使龙舟前进玩家(当前体力值)的路程。]],
  ["@jbs_zongzi"]="粽子",
  ["@jbs_zongzienergy"]="体力",
  ["#jbszongzi_rule"]="争粽",
  ["@jbszongzi_blueprocess"]="忠臣得分",
  ["@jbszongzi_redprocess"]="反贼得分",
  ["@jbszongzi_goalprocess"]="获胜目标",
  ["prezongzi"]="做粽子",
  ["zongzi_makezong"]="制粽",
  [":zongzi_makezong"]="出牌阶段限一次，你可以弃置若干张点数和为5的倍数的牌，获得x个粽子。(x=所弃牌点数和/5)",
}

return m_1v1_mode
